import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { useState, useCallback } from 'react';
/**
 * 管理列表增删元素、交换树脂、移动位置、重新赋值操作
 * @param options options.onChange 列表数据变更回调
 * @param options options.defaultList 列表数据默认值
 * @returns list 列表数据
 * @returns edit 编辑一条数据
 * @returns add 添加一条数据
 * @returns remove 删除一条数据
 * @returns exchange 交换元素位置
 * @returns move 移动元素位置
 * @returns setList 设置列表数据
 */
var useList = function useList(options) {
  var _ref = options || {},
    onChange = _ref.onChange,
    _ref$defaultList = _ref.defaultList,
    defaultList = _ref$defaultList === void 0 ? [] : _ref$defaultList;
  var _useState = useState(defaultList),
    _useState2 = _slicedToArray(_useState, 2),
    list = _useState2[0],
    setList = _useState2[1];
  /**
   * 全量变更
   * @param item
   */
  var triggerChange = useCallback(function (newList) {
    setList(newList);
    if (onChange) onChange(newList);
  }, [onChange]);
  /**
   * 编辑一项
   * @param item
   */
  var edit = useCallback(function (predicate, item) {
    var newList = list.map(function (it) {
      if (predicate(it)) {
        return item;
      } else {
        return it;
      }
    });
    triggerChange(newList);
  }, [list]);
  /**
   * 添加一项
   * @param item
   */
  var add = useCallback(function (item) {
    list.push(item);
    triggerChange(_toConsumableArray(list));
  }, [list]);
  /**
   * 删除一项
   * @param item
   */
  var remove = useCallback(function (item) {
    if (typeof item === 'number') {
      list.splice(item, 1);
      triggerChange(_toConsumableArray(list));
    } else {
      var newList = list.filter(function (it) {
        return item !== it;
      });
      triggerChange(newList);
    }
  }, [list]);
  /**
   * 交换位置
   * @param sourceIndex 源节点位置
   * @param targetIndex 目标位置
   */
  var exchange = useCallback(function (sourceIndex, targetIndex) {
    var temp = list[sourceIndex];
    list[sourceIndex] = list[targetIndex];
    list[targetIndex] = temp;
    triggerChange(_toConsumableArray(list));
  }, [list]);
  /**
   * 移动
   * @param sourceIndex
   * @param targetIndex
   */
  var move = useCallback(function (sourceIndex, targetIndex) {
    var source = list.splice(sourceIndex, 1)[0];
    if (sourceIndex < targetIndex) {
      // 下移
      list.splice(targetIndex, 0, source);
    } else {
      list.splice(targetIndex, 0, source);
    }
    triggerChange(_toConsumableArray(list));
  }, [list]);
  return {
    list: list,
    setList: triggerChange,
    edit: edit,
    add: add,
    remove: remove,
    exchange: exchange,
    move: move
  };
};
export default useList;